import axios from "axios";
import { MessageBox, Message } from "element-ui";
import { getToken, clearAll } from "@/utils/myAoth";
import router from "@/router";
// create an axios instance

const service = axios.create({
  baseURL: "https://leju.bufan.cloud", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor 断点
service.interceptors.request.use(
  (config) => {
    var token = getToken();
    //判断是否由token
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 返回断点
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    //如果秘钥不正确
    if (res.code === 20002) {
      //清空token和userinfo
      clearAll();
      //跳到登录页
      router.push("/login");
      //提示用户权限出错
      Message.error(res.message);
    }
    // if the custom code is not 20000, it is judged as an error.
    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
